﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace WebApplication1.MyFilters
{
    /// <summary>
    /// 自定义限流过滤器
    /// </summary>
    public class RateLimitFilter : IAsyncActionFilter
    {
        private readonly IMemoryCache _memoryCache;

        public RateLimitFilter(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }
        public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string remoteIp = context.HttpContext.Connection.RemoteIpAddress.ToString();
            string cacheKey = $"RateLimit_LastVisitTick_{remoteIp}";
            long? lastTick = _memoryCache.Get<long?>(cacheKey);
            // 如果缓存中存储的时间与当前时间相减差小于5秒则提示 请求频繁，否则正常执行
            if (lastTick == null || Environment.TickCount64 - lastTick > 5000)
            {
                _memoryCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));
                return next();
            }
            else
            {
                context.Result = new Microsoft.AspNetCore.Mvc.ContentResult()
                {
                    Content = "请求过于频繁，请稍后再试",
                    StatusCode = 429
                };
                return Task.CompletedTask;
            }
        }
    }
}